import React, { Component } from 'react'
import {
  View, TextInput, StyleSheet, Text, Image, SafeAreaView, Navigator, TouchableOpacity, Platform
} from 'react-native'
import NavBar from '../../components/PublicHeader';
import { Images } from '../../public/images/images'
import { LOGIN_BY_USERPWD, LOGIN_VERIFICATION_CODE, POST_APPPOSITION_ADD } from '../../public/WebApi/apiList';
import fetchWebApi from '../../public/WebApi/fetchBase';
import { Constant } from '../../public/js/constant';
import AsyncStorage from '@react-native-community/async-storage';
import { StackActions, NavigationActions } from 'react-navigation';
import getStorageValue from '../../utils/getStorageValue';
import fetch from '../../utils/fetch';
import platform from '../../utils/platform';
import action from '../../state/action';
import { setStorageValue } from '../../utils/storage';
import { Friend, Group } from '../../types/redux';
import { Actions } from 'react-native-router-flux'

// 弹窗提示
import Layer from '../../utils/Layer';
import { GetLocation } from '../../utils/GetLocation'
import { PermissionsAndroid } from 'react-native';
export default class register extends Component {
  constructor(props) {
    super(props)
    this.state = {
      userName: "",
      searchTexts: '',
      Loginjudgment: false,
      Passwordhiding: true,
      regular: false,
      longitude: 500,
      latitude: 500,
      positions: '',
      Logindelay: true
    }
  }


  async dili() {
    const {
      latitude,
      longitude,
      positions
    } = this.state
    if (latitude == 500 && longitude == 500) {
      console.log(latitude);
      return;
    } else {
      const res = await fetchWebApi(POST_APPPOSITION_ADD,

        {
          token: await getStorageValue(Constant.TOKEN),
          lat: latitude,
          lon: longitude,
          flag: "1",
          placeName: positions
        }, 'POST');
      // console.log("########## getUserMaillist########");
      // console.log(res);
      if (res.status == 200) {
        // console.log(this.state.DATAS)
        // this.setState({
        //   VerificationCode: res.data
        // })


      } else {
        Layer.showMsg(res.msg);
      }
    }

  }  //地理

  // 登录
  async userLogin() {
    const userData = { username: this.state.userName, password: this.state.searchTexts }
    const res = await fetchWebApi(LOGIN_BY_USERPWD, userData, 'POST');
    console.log("凸凸凸凸凸凸凸凸凸");
    console.log(res);
    // console.log("####### userLogin")
    // console.log(res)

    if (res.status === 200 && this.state.Loginjudgment == true) {
      //地址
      // 打开地图，获取经纬度
      // 保存token
      // console.log("@@@@@@")
      // console.log(res.data.token)
      await AsyncStorage.setItem(Constant.TOKEN, res.data.token);
      const [err, res2] = await fetch(
        'login',
        {
          username: userData.username,
          password: this.state.searchTexts,
          ...platform,
        },
      );
      console.log(res2);
      if (!err) {
        const user = res2;
        action.setUser(user);

        const linkmanIds = [
          ...user.groups.map((g: Group) => g._id),
          ...user.friends.map((f: Friend) => f._id),
        ];
        const [err2, linkmans] = await fetch('getLinkmansLastMessagesV2', {
          linkmans: linkmanIds,
        });
        if (!err2) {
          action.setLinkmansLastMessages(linkmans);
        }
        await setStorageValue(Constant.TOKENTWO, res2.token);
        Actions.maillist()
        this.dili()
        // 登录成功弹窗提示
        Layer.showMsg(res.msg);
        this.setState({ Logindelay: true })
        // this.props.navigation.push('MainStack')

        // 重构路由页面, 无法返回欢迎页面
        // 这里有几个就保留几个，点击完成后就会重构导航器
        // let resetActiom = StackActions.reset({
        //   index: 0, // 默认打开actions中的第几个页面
        //   actions: [
        //     NavigationActions.navigate({ routeName: 'message' }),
        //   ],
        // });

        // this.props.navigation.dispatch(resetActiom);

      } else {
        if (this.state.Loginjudgment == false) {
          // console.log("555")
          this.setState({ Logindelay: true })
          Layer.showMsg("请勾选协议");
        } else {
          this.setState({ Logindelay: true })
          Layer.showMsg(res.msg);
        }
        // 登录失败弹窗提示

      }
    }
  }
  //地理权限
  async requestLocationPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          //第一次请求拒绝后提示用户你为什么要这个权限
          'title': '我要地址查询权限',
          'message': '没权限我不能工作，同意就好了'
        }
      )

      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        // alert("你已获取了地址查询权限")
      } else {
        // alert("获取地址查询失败")
        this.requestLocationPermission()
      }
    } catch (err) {
      alert(err.toString())
    }
  }

  async componentDidMount() {
    if (Platform.OS === 'android') {
      await this.requestLocationPermission();
      this.getUserLocaltion();
    } else {
      Geolocation.requestAuthorization()
    }

    // handleChange()
  }

  async getUserLocaltion() {
    await GetLocation();
    setTimeout(() => {
      if (Object.keys(GetLocation()._55).length > 0) {
        this.setState({
          latitude: GetLocation()._55.latitude,
          longitude: GetLocation()._55.longitude,
          positions: GetLocation()._55.positions.aois[0].name
        })
        console.log('@@@@@@@@@@@@@@@');
        console.log(this.state.latitude, this.state.longitude, this.state.positions);
      } else {
        alert("获取地址失败，请重新进入系统！")
      }
    }, 3000)
  }

  onChangeText(text) {
    this.setState({
      userName: text
    })
  };
  onChangeTexts(text) {
    this.setState({
      searchTexts: text
    })
  };
  onClick() {
  }

  render() {
    //协议勾选
    const Agreementcheck = this.state.Loginjudgment == true ?
      <Image style={{ width: 15, height: 15, marginRight: 10 }} source={require('../../assets/images/search/Frameps.png')}></Image>
      : <Image source={require('../../assets/images/search/Ellipsess.png')} style={{ width: 15, height: 15, marginRight: 10 }}></Image>
    return (
      <View style={styles.container}>

        <View style={styles.containers}>
          <Text style={styles.Contenttext}>账号登录</Text>
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.onChangeText(text)}
            value={this.state.userName}
            placeholder={"请输入账号"}
          />
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.onChangeTexts(text)}
            value={this.state.searchTexts}
            placeholder={"请输入密码"}
            secureTextEntry={this.state.Passwordhiding}
          />
          {/* 密码隐藏 */}
          <TouchableOpacity style={styles.VerificationCode} onPress={() => (this.setState({
            Passwordhiding: !this.state.Passwordhiding
          }))}><Image source={require('../../assets/images/search/fexe.png')} ></Image></TouchableOpacity>
        </View>
        <View style={styles.middle}>
          <TouchableOpacity style={{ flexDirection: "row", alignItems: "center" }} onPress={() => { this.setState({ Loginjudgment: !this.state.Loginjudgment }) }} >
            {Agreementcheck}
            <Text>我已阅读</Text>
          </TouchableOpacity>
          <Text style={styles.colors}>《用户协议》</Text>
          <Text>和</Text>
          <Text style={styles.colors}>《平台协议》</Text>
        </View>
        <TouchableOpacity style={styles.tail} onPress={() => { if (this.state.Logindelay) { this.userLogin() }; this.setState({ Logindelay: false }) }}  >
          <Text style={styles.Login}>登录</Text>
        </TouchableOpacity>
        <View style={styles.tails}>
          <Text style={styles.Tailcolor} onPress={() => { this.props.navigation.push('register') }}>用户注册 </Text>
          <Text style={styles.Tailcolor} onPress={() => { this.props.navigation.push('forgetPwd') }}>忘记密码</Text>
        </View>
      </View >
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingLeft: 40,
    paddingRight: 40,
    backgroundColor: "#fff"
  },
  layer: {
    display: 'flex',
    justifyContent: 'space-around'
    , alignItems: 'center',
    flexDirection: 'row',
    marginTop: 120

  },
  Textred: {
    color: 'white'
  },
  inputSearchBox: {
    justifyContent: "center",
    height: 40,
    width: "100%",
    backgroundColor: 'rgba(232, 236, 240, 0.5)',
    marginTop: 25,
    borderRadius: 20,
  },
  inputSearch: {
    paddingLeft: 20,
    paddingRight: 20,
    fontSize: 14,
    color: 'rgba(0, 0, 0, 0.31)'
    // TextIndent: 20
  },
  containers: {
    marginTop: '25%',
    marginBottom: '8%'
  },
  move: {
    marginLeft: '8%'
  },
  Contenttext: {
    fontSize: 24,
    color: '#000000',
    fontWeight: 'bold',
  },
  Contenttexts: {
    fontSize: 13,
    color: 'rgba(0, 0, 0, 0.56)',
    marginLeft: 45,
    marginTop: 5,
    fontWeight: 'bold'
  },
  VerificationCode: {
    marginTop: 20,
    color: '#4C6BDC',
    textAlign: 'center',
    position: 'absolute',
    right: "10%",
    borderBottomRightRadius: 10,
    borderTopRightRadius: 10,
    fontSize: 15
  },
  colors: {
    color: '#4C6BDC'
  },
  Login: {
    fontSize: 18,
    color: '#FFF'
  },
  middle: {
    flexDirection: 'row',
    alignItems: "center",
    marginTop: 20,
  },
  tail: {
    width: '100%',
    marginTop: 30,
    justifyContent: "center",
    alignItems: 'center',
    backgroundColor: '#1890FF',
    height: 40,
    borderRadius: 50,
  },
  tails: {
    marginTop: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  Tailcolor: {
    fontSize: 12,
    color: 'rgba(0, 0, 0, 0.5)'
  },
  Agreementcheck: {
    width: 16,
    height: 16,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#1890FF",
    borderRadius: 50,
    marginRight: 10
  }

})